/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hathor.networking.reciever;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;

/**
 *
 * @author Kenneth
 */
public class BatchExecutor implements Runnable {

    private final File batchFile;
    private Process process;

    public BatchExecutor(File batchFile) {
        this.batchFile = batchFile;
    }

    private void executeBatch() throws IOException, InterruptedException {
        if (process == null) {
            System.out.println("Executing batch");
            process = Runtime.getRuntime().exec(batchFile.getAbsolutePath());
            InputStream ois = process.getInputStream();
            InputStream eis = process.getErrorStream();
            InputStream mergedInputStream = new SequenceInputStream(ois, eis);
            BufferedReader processOutputStream = new BufferedReader(new InputStreamReader(mergedInputStream));
            String line;
            while ((line = processOutputStream.readLine()) != null) {
                System.out.println(line);
            }
            process.waitFor();

        } else {
            System.out.println("A batch is already running");
        }

    }

    @Override
    public void run() {
        try {
            executeBatch();
        } catch (IOException | InterruptedException ex) {
            System.err.println("Could not execute batchcommand");
        }
    }

    void terminate() {
        if (process != null) {
            process.destroy();
            process = null;
            Thread.currentThread().interrupt();
        }
    }
}
